﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using com.kmer.Cache;
using com.kmer.Helper;
using com.kmer.Security;
using com.kmer.db;

// ReSharper disable once CheckNamespace
namespace com.kmer.ApiServer
{
    /// <summary>
    /// 认证
    /// </summary>
    public class TokenHandler : BaseHandler
    {
        /// <summary>
        /// 获取API 访问凭据（AccessToken）
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        [Description("获取系统Token（System AccessToken）")]
        [ReturnType(typeof(SystemAccessToken))]
        [ApiVersion("1.0.0")]
        public ApiResult Get([ParamDescription("应用ID")]string appid,
            [ParamDescription("访问密钥")]string secret)
        {
            Guid guid;
            if (Guid.TryParse(appid, out guid) == false)
            {
                throw new ArgumentException("无效的AppID", nameof(appid));
            }
            using (var dc = new km_platformEntities())
            {
                var app = dc.yhAPIApp.FirstOrDefault(item => item.ID == guid && item.AppSecret == secret);
                if (app == null)
                {
                    return Error("无效请求", 404);
                }
                var token = APIHandlerFactory.createAccessToken(app.ID, app.AppSecret);
                RedisCache.AddString(token, app.ToJson(), 120);
                //myCache.Insert(token, app.ToJson(), Timeout, CacheItemPriority.Default);
                return Success(new SystemAccessToken
                {
                    AccessToken = token,
                    TimeOut = Timeout
                });
            }
        }
        /// <summary>
        /// 初始化主站的API配置信息
        /// </summary>
        public static string InitWebAccessToken(bool cache = false)
        {
            var cacheKey = "WEB-SITE-APP-INFO:" + MD5.Compute(HttpContext.Current.Server.MapPath("~/"));
            if (cache)
            {
                if (RedisCache.Exists(cacheKey))
                {
                    var token = RedisCache.GetString(cacheKey);
                    if (RedisCache.Exists(token))
                        return token;
                }
            }
            using (var dc = new km_platformEntities())
            {
                var app = dc.yhAPIApp.FirstOrDefault(item => item.AppType == 0);
                if (app == null)
                {
                    throw new Exception("请配置主站的App信息");
                }
                var token = APIHandlerFactory.createAccessToken(app.ID, app.AppSecret);
                RedisCache.AddString(token, app.ToJson(), Timeout);
                RedisCache.AddString(cacheKey, token, Timeout);
                return token;
            }
        }
        /// <summary>
        /// 系统SystemAccessToken
        /// </summary>
        public class SystemAccessToken
        {
            /// <summary>
            /// AccessToken
            /// </summary>
            [ParamDescription("System AccessToken")]
            public string AccessToken { get; set; }

            /// <summary>
            /// 超时时间，从请求的时间起。单位（秒）
            /// </summary>
            [ParamDescription("超时时间，从请求的时间起。单位（秒）", DefaultValue = 7200)]
            public int TimeOut { get; set; }
        }
    }
}
